<?php
namespace Modules\Core\Controllers;

use Core\File;
use Core\Mvc\Controller;
use Core\Module;
use Core\Theme;
use Core\Paginator\Adapter\Collection as CollectionPaginator;
use Modules\Core\Models\Log;
use Phalcon\Version;

class AdminController extends Controller
{

    public function frameAction()
    {
        self::$variables += array(
            '#templates' => 'adminFrame',
            'title' => '后台管理框架',
            'fullUrl' => $this->request->getHTTPReferer(),
            'adminMenu' => array(
                '#templates' => 'adminMenu',
                'data' => $this->config->cache('menuData'),
                'hierarchy' => $this->config->cache('menuHierarchy'),
            ),
        );
    }

    public function indexAction()
    {
        $content = array();
        self::$variables += array(
            'description' => '管理概况',
            'title' => '控制台',
            'breadcrumb' => array(),
            'content' => &$content,
        );
        // 添加编辑菜单
        $content['serverInfo'] = array(
            '#templates' => 'box',
            'title' => '服务器信息',
            'max' => false,
            'wrapper' => true,
            'color' => 'primary',
            'size' => '6',
            'content' => array(
                '#templates' => array(
                    'table',
                ),
                'theadDisplay' => false,
                'thead' => array(
                    '项目',
                    '信息',
                ),
                'checkAll' => false,
                'data' => array(
                    'serverInfo' => array(
                        '操作系统：',
                        php_uname('s') . ' ' . php_uname('r'),
                    ),
                    'phpVersion' => array(
                        'php版本：',
                        phpversion(),
                    ),
                    'serverIp' => array(
                        '服务器IP：',
                        $this->request->getServerAddress(),
                    ),
                    'phpMemory' => array(
                        'php可用内存：',
                        get_cfg_var("memory_limit"),
                    ),
                    'phalconVersion' => array(
                        'phalcon版本',
                        Version::get(),
                    ),
                ),
            ),
        );
    }

    public function logAction($page)
    {
        $query = [
            'sort' => [
                'created' => -1,
            ],
            'limit' => 30,
            'skip' => 30 * ($page - 1),
        ];
        $data = Log::find($query);

        $dataPagination = new CollectionPaginator([
            'data' => $data,
            'query' => $query,
            'page' => $page,
            'collection' => '\Modules\Core\Models\Log',
        ]);

        self::$variables += array(
            'module' => '系统',
            'title' => '日志',
            'description' => '日志记录列表',
            'breadcrumb' => array(
                'admin' => array(
                    'href' => array(
                        'for' => 'adminIndex',
                    ),
                    'name' => '控制台',
                ),
            ),
            'content' => array(),
        );
        self::$variables['content']['list'] = array(
            '#templates' => 'adminLogList',
            'data' => $dataPagination->getPaginate()
        );
    }

    public function logDeleteAction($id)
    {
        $log = Log::findById($id);
        if ($log) {
            if ($log->delete()) {
                $this->flashSession->success('删除成功');
            } else {
                $this->flashSession->error('删除失败：' . $id);
            }
        } else {
            $this->flashSession->error('删除失败，数据不存在');
        }
        return $this->temMoved(['for' => 'adminLog', 'page' => 1]);
    }

    public function modulesAction()
    {
        $enabledModules = $this->config->get('modules');
        $modulesList = Module::listInfo();
        self::$variables += array(
            'title' => '模块',
            'description' => '本地模块列表，启用、禁用、删除',
            '#templates' => 'page',
            'breadcrumb' => array(
                'module' => array(
                    'name' => '模块',
                ),
            ),
            'content' => array(
                'modulesList' => array(
                    '#templates' => 'adminModules',
                    'data' => $modulesList,
                    'enabledModules' => $enabledModules
                ),
            ),
        );
    }

    public function securityAction()
    {
        $securityList = $this->config->cache('securityAction');
        $security = $this->config->get('security');
        $roles = $this->entityManager->contentModel('user');
        if ($this->request->isPost()) {
            $data = $this->request->getPost();
            $security = array();
            foreach ($securityList as $sk => $sv) {
                $security[$sk] = array();
                foreach ($roles as $rk => $rv) {
                    if (isset($data[$sk][$rk])) {
                        $security[$sk][$rk] = true;
                    } else {
                        $security[$sk][$rk] = false;
                    }
                }
            }
            if ($this->config->set('security', $security)) {
                $this->flashSession->success('权限策略保存成功');
            } else {
                $this->flashSession->error('权限策略保存失败');
            }
        }
        self::$variables += array(
            'module' => '系统',
            'title' => '安全设置',
            'description' => '权限策略设置',
            'breadcrumb' => array(
                'admin' => array(
                    'href' => array(
                        'for' => 'adminIndex',
                    ),
                    'name' => '控制台',
                ),
            ),
            'content' => [],
        );
        self::$variables['content']['list'] = array(
            '#templates' => 'security',
            'securityList' => $securityList,
            'roles' => $roles,
            'security' => $security,
        );
    }

    public function modulesUninstallAction($module)
    {
        Module::uninstall($module);
        return $this->temMoved(['for' => 'adminModules']);
    }

    public function modulesEnableAction($module)
    {
        Module::enable($module);
        return $this->temMoved(['for' => 'adminModules']);
    }

    public function modulesDisableAction($module)
    {
        Module::disable($module);
        return $this->temMoved(['for' => 'adminModules']);
    }

    public function themesAction()
    {
        $themesList = Theme::listInfo();
        $enableThemes = $this->config->get('themes');
        self::$variables += array(
            'title' => '主题',
            'description' => '本地主题列表，启用、禁用、删除',
            '#templates' => 'page',
            'breadcrumb' => array(
                'module' => array(
                    'name' => '主题',
                ),
            ),
            'content' => array(
                'modulesList' => array(
                    '#templates' => 'adminThemes',
                    'data' => $themesList,
                    'enableThemes' => $enableThemes
                ),
            ),
        );
    }

    public function themesEnableAction($theme, $controller)
    {
        Theme::enable($theme, $controller);
        return $this->temMoved(['for' => 'adminThemes']);
    }

    public function themesUninstallAction($theme)
    {
        Theme::uninstall($theme);
        return $this->temMoved(['for' => 'adminThemes']);
    }

    public function cacheAction($handle, $type)
    {
        $cacheList = $this->config->get('cache');
        if ($handle == 'clear') {
            if (isset($cacheList[$type])) {
                $state = File::clearCache($type);
                if (!$state) {
                    $this->flash->error($state);
                } else {
                    $this->flash->success('缓存删除成功');
                }
            }
        }
        self::$variables = array(
            '#templates' => 'page',
            'title' => '缓存',
            'description' => '缓存列表',
            'pageTabs' => array(),
            'breadcrumb' => array(
                'admin' => array(
                    'href' => array(
                        'for' => 'adminIndex',
                    ),
                    'name' => '控制台',
                ),
                'cache' => array(
                    'name' => '缓存',
                ),
            ),
            'content' => array(
                '#templates' => 'cache',
                'cacheList' => $cacheList,
            ),
        );
    }
}
